package com.loper7.base.widget.prcturebrows;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.loper7.base.R;
import com.loper7.base.adapter.ShowImagesAdapter;
import com.loper7.base.utils.DisplayUtil;
import com.loper7.base.utils.img.ImageLoad;
import com.loper7.base.widget.dialog.SpinView;
import com.luck.picture.lib.photoview.PhotoView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/5/3.
 * 嵌套了viewpager的图片浏览
 */

public class ImageBrowser<T extends Object> extends Dialog {

    private View mView;
    private Context mContext;
    private ShowImagesViewPager mViewPager;
    private TextView mIndexText;
    private ImageView btnClose, btnDownload;

    private List<View> mViews;
    private ShowImagesAdapter mAdapter;
    private Object nowImage;

    public ImageBrowser(@NonNull Context context) {
        super(context, R.style.imageBrowseBgDialog);
        this.mContext = context;
        mViews = new ArrayList<>();

        initView();
    }

    private void initView() {
        mView = View.inflate(mContext, R.layout.dialog_images_brower, null);
        mViewPager = (ShowImagesViewPager) mView.findViewById(R.id.vp_images);
        mIndexText = (TextView) mView.findViewById(R.id.tv_image_index);
        btnClose = mView.findViewById(R.id.btn_close);
        btnDownload = mView.findViewById(R.id.btn_download);
        btnDownload.setVisibility(View.GONE);

        mViewPager.setPageMargin(DisplayUtil.dip2px(getContext(), 10));

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageLoad.savePictureToast(getContext(), nowImage.toString());
                btnDownload.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(mView);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        window.setWindowAnimations(R.style.browser_push_anim);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = 0;
        wl.height = getWindowDisplayMetrics().heightPixels;
        wl.width = getWindowDisplayMetrics().widthPixels;
        wl.gravity = Gravity.CENTER;
        wl.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        window.setAttributes(wl);
    }

    /**
     * 设置数据
     *
     * @param mDatas
     * @return
     */
    public ImageBrowser setDatas(@NonNull final List<T> mDatas) {
        mViews.clear();

        if (mDatas == null || mDatas.size() <= 0)
            return this;

        for (int i = 0; i < mDatas.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_images_item, null);
            PhotoView photoView = view.findViewById(R.id.photoView);
            final SpinView spinView = view.findViewById(R.id.spinView);
            ImageLoad.load(getContext(), photoView, mDatas.get(i), new RequestListener() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                    spinView.setVisibility(View.GONE);
                    return false;
                }
            });
            photoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dismiss();
                }
            });
            mViews.add(view);
        }

        mAdapter = new ShowImagesAdapter(mViews);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mViews.size());
        mIndexText.setText(1 + " / " + mDatas.size());
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                nowImage = mDatas.get(position);
                mIndexText.setText((position + 1) + " / " + mDatas.size());
                if (mDatas.get(position) instanceof String && !ImageLoad.fileIsExists(getContext(),
                        ImageLoad.url2ImageName(mDatas.get(position).toString())))
                    btnDownload.setVisibility(View.VISIBLE);
                else
                    btnDownload.setVisibility(View.GONE);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if (mDatas.get(0) instanceof String && !ImageLoad.fileIsExists(getContext(), ImageLoad.url2ImageName(mDatas.get(0).toString())))
            btnDownload.setVisibility(View.VISIBLE);
        else
            btnDownload.setVisibility(View.GONE);
        nowImage = mDatas.get(0);

        return this;
    }

    /**
     * 显示指定表图片
     *
     * @param index
     */
    public void show(int index) {
        super.show();
        if (mViewPager != null && index < mViews.size())
            mViewPager.setCurrentItem(index, false);
    }

//        /**
//     * 设置加载图片监听
//     *
//     * @param loadAdapter
//     */
//    public ImageBrowser setLoadAdapter(LoadAdapter loadAdapter) {
//        if (loadAdapter != null && mViews != null) {
//            for (int i = 0; i < mViews.size(); i++) {
//                loadAdapter.loadImage(this, (PhotoView) mViews.get(i).findViewById(R.id.photoView), mDatas.get(i), i);
//            }
//        }
//        return this;
//    }
//
//    /**
//     * 适配器，在 loadImage 方法中填充数据
//     *
//     * @param <T> item 数据模型
//     */
//    public interface LoadAdapter<T> {
//        void loadImage(ImageBrowser showImagesDialog, PhotoView photoView, T model, int position);
//    }


    public DisplayMetrics getWindowDisplayMetrics() {
        DisplayMetrics metrics = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }


}
